package com.example.lin.http;

import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @className: RestTemplateProxy
 * @description:
 * @author: Lin.Gu
 * @date: 2025-11-03  13:38
 */
public class RestTemplateProxy {

    /**
     * 静态成员变量，用于存储RestTemplate实例
     */
    private static volatile RestTemplate restTemplate;
    private static final Object lock = new Object();

    // 公共线程池配置
    private static final ExecutorService COMMON_EXECUTOR = new ThreadPoolExecutor(
            10,  // 核心线程数
            30, // 最大线程数
            60L, TimeUnit.SECONDS,  // 空闲线程存活时间
            new LinkedBlockingQueue<>(100), // 任务队列
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
    );

    /**
     * 获取RestTemplate实例
     *
     * @return RestTemplate 实例
     */
    public static RestTemplate getRestTemplate() {
        if (restTemplate == null) {
            synchronized (lock) {
                if (restTemplate == null) {
                    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
                    factory.setConnectTimeout(30000); // 连接超时（30秒）
                    factory.setReadTimeout(60000); // 读取超时（60秒）
                    restTemplate = new RestTemplate(factory);
                }
            }
        }
        return restTemplate;
    }

    /**
     * 获取公共线程池
     *
     * @return ExecutorService 线程池实例
     */
    public static ExecutorService getCommonExecutor() {
        return COMMON_EXECUTOR;
    }


}
